package com.kingyun.gpsinspection.purificationservice.services.som.innerservice.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.cqhilink.api.common.utils.date.DateStyle;
import com.cqhilink.api.common.utils.date.DateUtil;
import com.cqhilink.api.common.utils.enums.RespCodeEnum;
import com.kingyun.gpsinspection.purificationservice.common.constant.BackMessage;
import com.kingyun.gpsinspection.purificationservice.common.utils.ETUtils;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.som.ElectronTemplateItemMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.som.ElectronTemplateMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.som.ElectronTemplateValueMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.som.ElectronTemplate;
import com.kingyun.gpsinspection.purificationservice.facade.model.som.ElectronTemplateItem;
import com.kingyun.gpsinspection.purificationservice.facade.model.som.ElectronTemplateValue;
import com.kingyun.gpsinspection.purificationservice.facade.model.webservicesmodel.EntityValue;
import com.kingyun.gpsinspection.purificationservice.facade.service.som.SomElectronTemplateService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Author 卢曼成
 * @Description 电子模版实现类
 * @CreateDateTime 2017-06-05 17:11
 **/
public class SomElectronTemplateServiceImpl implements SomElectronTemplateService {
    private static Logger logger = LoggerFactory.getLogger(InOutServiceImpl.class);
    @Autowired
    private ElectronTemplateMapper electronTemplateMapper;
    @Autowired
    private ElectronTemplateItemMapper electronTemplateItemMapper;
    @Autowired
    private ElectronTemplateValueMapper electronTemplateValueMapper;
    @Value("#{configProperties['ElectronTemplateDate']}")
    private String electronTemplateDate;


    /**
     * 分页查询
     *
     * @param param
     * @return
     */
    @Override
    public Map<String, Object> findPageList(ElectronTemplate param) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        if (StringUtils.isEmpty(param.getOrgId())) {
            return map;
        }
        map.put("rows", electronTemplateMapper.queryList(param));
        map.put("total", electronTemplateMapper.queryCount(param));
        return map;
    }

    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance(); //得到日历
        calendar.setTime(new Date());//把当前时间赋给日历
        calendar.add(Calendar.DAY_OF_MONTH, -2);  //设置为前一天
        System.out.println(DateUtil.DateToString(calendar.getTime(), DateStyle.YYYY_MM_DD));
        Date date = new Date();
        System.out.println(date.getHours() > 5);
//        System.out.println(2017 >= 2018);
//        System.out.println(ETUtils.bottomMonth(new Date(),1));
//        System.out.println(ETUtils.firstMonth(new Date()));
//        System.out.println(ETUtils.getYearLast(2017, -1));
//        Calendar calendar = Calendar.getInstance();
//        System.out.println(calendar.get(Calendar.YEAR));
    }
    /**
     * 模版巡检记录查询集合
     *
     * @param param
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> findValuePageList(ElectronTemplate param) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        if (StringUtils.isEmpty(param.getOrgId())) {
            return map;
        }
        List<ElectronTemplate> list = electronTemplateMapper.queryList(param);
        int year = ETUtils.year();
        int newYear = year + 1;
        int yearCount = ETUtils.isPingnian(year);//判断是否闰年平年天数
        Date date = new Date();
        String lastMonday = ETUtils.lastMonday(date);//上周周一
        String lastSunday = ETUtils.lastSunday(date);//上周周日
        String firstMonth = ETUtils.firstMonth(date);//上月第一天
        String bottomMonth = ETUtils.bottomMonth(date, 1);//上月最后一天
        String currYearFirst = ETUtils.getYearFirst(year);//当前年份第一天
        String currYearLast = ETUtils.getYearLast(newYear);//当前年份最后一天
        String thisDateTime;
        String lastDateTime;
        if(date.getHours() > 7){
            thisDateTime = ETUtils.getFrontDate(date,-1);//获取当前日期前一天
            lastDateTime = DateUtil.DateToString(date,DateStyle.YYYY_MM_DD);//获取今天日期
        }else{
            thisDateTime = ETUtils.getFrontDate(date,-2);//获取当前日期前一天
            lastDateTime = ETUtils.getFrontDate(date,-1);//获取今天日期
        }
        int monthMaxDay = ETUtils.getMonthMaxDay(-1);//上月最后一天

//        if (StringUtils.isNotEmpty(electronTemplateDate)) {
//            String[] str = electronTemplateDate.split("-");
//            if (str.length == 3) {
//                int year2 = Integer.parseInt(str[0]);
////                int month = Integer.parseInt(str[1]);
////                if (year2 > year) {
////                    yearCount = ETUtils.getYearSize(electronTemplateDate, ETUtils.getYearLast(year));
////                }
////                if (month > 0) {
////                    monthMaxDay = (monthMaxDay - month) + 1;
////                }
//            }
//        }

        for (ElectronTemplate et : list) {
            //查询前一天数据
            ElectronTemplateValue etv1 = new ElectronTemplateValue();
            etv1.setStartDateTime(thisDateTime + " 08:00:00");
            etv1.setEndDateTime(lastDateTime + " 07:59:59");
            etv1.setEtId(et.getEtId());
            //查询前一周，周一到周日
            ElectronTemplateValue etv2 = new ElectronTemplateValue();
            etv2.setStartDateTime(lastMonday + " 08:00:00");
            etv2.setEndDateTime(lastSunday + " 07:59:59");
            etv2.setEtId(et.getEtId());
            //查询当前月份，一号到最后一天数据
            ElectronTemplateValue etv3 = new ElectronTemplateValue();
            etv3.setStartDateTime(firstMonth + " 08:00:00");
            etv3.setEndDateTime(bottomMonth + " 07:59:59");
            etv3.setEtId(et.getEtId());
            //当前年份第一天和最后一天
            ElectronTemplateValue etv4 = new ElectronTemplateValue();
            etv4.setStartDateTime(currYearFirst + " 08:00:00");
            etv4.setEndDateTime(currYearLast + " 07:59:59");
            etv4.setEtId(et.getEtId());
            int size1 = electronTemplateValueMapper.selectDateTimeCount(etv1);
            int size2 = electronTemplateValueMapper.selectDateTimeCount(etv2);
            int size3 = electronTemplateValueMapper.selectDateTimeCount(etv3);
            int size4 = electronTemplateValueMapper.selectDateTimeCount(etv4);
            et.setDayRate(ETUtils.calculation(1, 24, size1));
            et.setMonthRate(ETUtils.calculation(7, 24, size2));
            et.setWeekRate(ETUtils.calculation(monthMaxDay, 24, size3));
            et.setYearRate(ETUtils.calculation(yearCount, 24, size4));
        }
        map.put("rows", list);
        map.put("total", electronTemplateMapper.queryCount(param));
        return map;
    }

    /**
     * 根据ID查询
     *
     * @param etId
     * @return
     */
    @Override
    public Map<String, Object> getByParam(String etId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", electronTemplateMapper.selectByPrimaryKey(etId));
        return map;
    }

    /**
     * 根据ID查询
     *
     * @param etId
     * @return
     * @throws Exception
     */
    @Override
    public ElectronTemplate getById(String etId) throws Exception {
        if (StringUtils.isEmpty(etId)) {
            return null;
        }
        return electronTemplateMapper.selectByPrimaryKey(etId);
    }

    /**
     * 保存
     *
     * @param param
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> save(ElectronTemplate param) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String id = UniqueUtil.uuid();
        Date date = new Date();
        param.setEtId(id);
        param.setCreateTime(date);
        param.setModifyTime(date);
        List<ElectronTemplateItem> eiList = JSONArray.parseArray(param.getHead(), ElectronTemplateItem.class);
        if (eiList != null && eiList.size() > 0) {
            for (ElectronTemplateItem eti : eiList) {
                eti.setCreateTime(date);
                eti.setModifyTime(date);
                eti.setCreatorId(param.getCreatorId());
                eti.setModifyerId(param.getCreatorId());
                eti.setEtiId(UniqueUtil.uuid());
                eti.setEtId(id);
            }
        }
        try {
            int num = electronTemplateMapper.insertSelective(param);
            if (eiList != null && eiList.size() > 0) {
                electronTemplateItemMapper.insertList(eiList);
            }
            map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", num > 0 ? BackMessage.ADD_OK : BackMessage.ADD_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", BackMessage.ADD_FAIL);
        }
        return map;
    }

    /**
     * 修改
     *
     * @param param
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> update(ElectronTemplate param) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Date date = new Date();
        param.setModifyTime(date);
        List<String> delList = JSONArray.parseArray(param.getDelEtiIds(), String.class);
        List<ElectronTemplateItem> list = JSONArray.parseArray(param.getHead(), ElectronTemplateItem.class);
        List<ElectronTemplateItem> addList = null;
        List<ElectronTemplateItem> upList = null;
        if (list != null && list.size() > 0) {
            addList = new ArrayList<ElectronTemplateItem>();
            upList = new ArrayList<ElectronTemplateItem>();
            for (ElectronTemplateItem eti : list) {
                eti.setModifyTime(date);
                eti.setModifyerId(param.getModifyerId());
                eti.setEtId(param.getEtId());
                if (StringUtils.isNotEmpty(eti.getEtiId())) {
                    upList.add(eti);
                } else {
                    eti.setCreateTime(date);
                    eti.setCreatorId(param.getModifyerId());
                    eti.setEtiId(UniqueUtil.uuid());
                    addList.add(eti);
                }
            }
        }
        try {
            int num = electronTemplateMapper.updateByPrimaryKeySelective(param);
            if (upList != null && upList.size() > 0) {
                electronTemplateItemMapper.updateList(upList);
            }
            if (addList != null && addList.size() > 0) {
                electronTemplateItemMapper.insertList(addList);
            }
            if (delList != null && delList.size() > 0) {
                electronTemplateItemMapper.deleteKeyList(delList);
                electronTemplateValueMapper.deleteETIIdList(delList);
            }
            map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", num > 0 ? BackMessage.MODIFY_OK : BackMessage.MODIFY_FAIL);
        } catch (Exception e) {
            logger.error("ElectronTemplate 修改出错" + e.getMessage());
            e.printStackTrace();
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", BackMessage.MODIFY_FAIL);
        }
        return map;
    }

    /**
     * 逻辑删除
     *
     * @param etId
     * @return
     */
    @Override
    public Map<String, Object> deleteKey(String etId) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> list = JSONArray.parseArray(etId, String.class);
        try {
            int num = electronTemplateMapper.deleteKeyList(list);
            map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", num > 0 ? BackMessage.DEL_OK : BackMessage.DEL_FAIL);
        } catch (Exception e) {
            logger.error("ElectronTemplate 删除出错" + e.getMessage());
            e.printStackTrace();
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", BackMessage.DEL_FAIL);
        }
        return map;
    }

    /**
     * 根据模版版本etvId查询集合信息, 注意：该方法只是用来给电子巡检记录调用的。
     *
     * @param etvId
     * @return
     */
    public List<ElectronTemplate> selectETVIdList(String etvId) {
//        List<ElectronTemplate> etList = electronTemplateMapper.selectETVIdList(etvId);
        List<ElectronTemplate> etList = null;
        if (etList == null || etList.size() == 0) {
            return etList;
        }
        List<String> itemName = new ArrayList<String>();
        for (ElectronTemplate et : etList) {
//            itemName.add(et.getOpc());
        }
        String sb = "{\"itemName\":" + JSONArray.toJSON(itemName) + "}";
//                sb = "{\"itemName\":[\"Channel1.Device1.12345678901234567\",\"Channel1.Dvice1.12345678901234568\"]} ";
        String str = null;
        try {
            //处理连接超时
//            str = HttpClientUtil.httpPostWithJson(configUril, sb);
        } catch (Exception e) {
            return etList;
        }
//                str = "{\"value\": [[\"1\", 129011111111111.0132132132132, \"Good\", \"05/03/17 10:27:45\"], [\"2\", \"1.13213213213213\", \"Good\", \"05/03/17 10:27:45\"],[\"3\", \"1.13213132132\", \"Good\", \"05/03/17 10:27:45\"]" +
//                        "[\"4\", \"12345.132132465\", \"Good\", \"05/03/17 10:27:45\"],[\"5\", \"365465.0054564646\", \"Good\", \"05/03/17 10:27:45\"]]}";
        if (StringUtils.isNotEmpty(str) && str.contains("value")) {
            EntityValue ev = JSONObject.parseObject(str, EntityValue.class);
            List<String> list = ev.getValue();
            if (list != null && list.size() > 0) {
                for (ElectronTemplate et : etList) {
//                    et.setOpcValue(isValue(list, et.getOpc()));
                }
            }
        }
        return etList;
    }


    /**
     * 处理特性值对应OPC值
     *
     * @param list
     * @param opcId
     * @return
     */
    private String isValue(List<String> list, String opcId) {
        for (String s : list) {
            List<String> strList = JSONArray.parseArray(s, String.class);
            if (strList.get(0).equals(opcId)) {
                return strList.get(1);
            }
        }
        return null;
    }
}
